local skynet = require "skynet"
local filelog = require "filelog"
local helperbase = require "helperbase"
local socket = require "socket"
local servicepoolmng = require "incrservicepoolmng"


local GmsvrHelper = helperbase:new({}) 

function GmsvrHelper:init_agent_pool(conf)	
	self.server.agent_pool = servicepoolmng:new({}, {service_name="agent", service_size=conf.agentsize, incr=conf.agentincr}, "")
end


function GmsvrHelper:close_http_session(id)
	local http_session = self.server.http_sessions[id]
	if http_session ~= nil then
		self.server.agent_pool:delete_service(id)
		if http_session.client_fd ~= nil then
			socket.close(http_session.client_fd)
		end
		self.server.http_sessions[id] = nil
	end
end

function GmsvrHelper:open_http_server(conf)
	local ip
	local port
	local http_session
	if conf.gmhttpsvr_ip == nil then
		ip = "0.0.0.0"
	else
		ip = conf.gmhttpsvr_ip
	end

	if conf.gmhttpsvr_port == nil then
		port = 8081
	else
		port = conf.gmhttpsvr_port
	end
	
	if self.server.server_socket_fd ~= 0 then
		socket.close(self.server.server_socket_fd)
		self.server.server_socket_fd = 0
	end
	self.server.server_socket_fd = socket.listen(ip, port)

	socket.start(self.server.server_socket_fd , function(client_fd, addr)
		http_session = self.server.agent_pool:create_service()
		if http_session == nil then
			filelog.sys_error("GmsvrHelper.open_http_server: self.server.agent_pool:create_service failed", client_fd, addr)
			socket.close(client_fd)
		else
			http_session.client_fd = client_fd
			self.server.http_sessions[http_session.id] = http_session
			skynet.send(http_session.service, "lua", "cmd", "start", http_session.id, {client = client_fd, watchdog = skynet.self()})
			skynet.send(http_session.service, "lua", "request", "callback", client_fd)
		end
	end)
end

return	GmsvrHelper  
